package com.zzz.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.zzz.common.core.constants.Constants;
import com.zzz.common.core.constants.HttpConstants;
import com.zzz.common.core.utils.ThreadLocalUtil;
import com.zzz.common.security.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @BelongsProject: oj-project
 * @BelongsPackage: com.zzz.common.security.interceptor
 * @Author: zhai
 * @CreateTime: 2025-10-12  17:04
 * @Description: TODO
 * @Version: 1.0
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret; // 从哪个服务配置文件中读取，取决于这个bean对象交给那个服务的spring容器进行管理

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 当调用login接口时，会调用这个方法
        String token = getToken(request);
        if (StrUtil.isEmpty(token)) {
            return true;
        }
        Long userId = tokenService.getUserId(token, secret);
        ThreadLocalUtil.set(Constants.USER_ID, userId);
        tokenService.extendToken(token, secret);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return token;
    }
}
